<?php
class SubjectsController extends Zend_Controller_Action
{
	
    public function init()
    {
    	Zend_Loader::loadClass('LoginDefaultModel');
    	Zend_Loader::loadClass('SubjectsModel');
    	Zend_Loader::loadClass('TeacherModel');
    	Zend_Loader::loadClass('ExercisesModel');
    	Zend_Loader::loadClass('Zend_Session');
    	Zend_Loader::loadClass('Zend_Session_Namespace');
        Zend_Loader::loadClass('PointModel');
        Zend_Loader::loadClass('StudentsModel');
        Zend_Loader::loadClass('InfoClassModel');
    }
    
    public function preDispatch(){
    	
    	/*
    	 * Load template
    	*/
    	$layoutPath = APPLICATION_PATH  . '/templates/default/default';
    	$option = array (	'layout' 		=> 'index',
    			'layoutPath' 	=> $layoutPath );
    	Zend_Layout::startMvc ( $option );
    	
    	$this->view->module = $this->_request->getModuleName();
    	$this->view->controller =  $this->_request->getControllerName();
    	$this->view->action =  $this->_request->getActionName();
    	
    	$lgNamespace = new Zend_Session_Namespace('enrol_teacher');
    	$auth = Zend_Auth::getInstance();
        if(($lgNamespace->enrol_teacher !=1) || !($auth->hasIdentity())){
            echo "Not enrol";die;
        }
    }
    
    function indexAction(){
    	$sj_id = $this->_request->getParam('s_id');
    	if($sj_id){
    		$list = SubjectsModel::getExercisesOfSubject($sj_id);
    		$this->view->sj_name = SubjectsModel::getNameSubject($sj_id);
    		$this->view->list = $list;
    		$this->view->sj_id = $sj_id;
    	}
    }
    
    function addExercisesAction(){
    	$sj_id = $this->_request->getParam('sj_id');
    	
    	if($this->_request->isPost()){
    		/*
    		 * Nhan du lieu dau vao
    		 */
    		$exercises["name"] = $this->_request->getParam('exercises');
    		$exercises["id_subjects"] = $sj_id;
    		$exercises["time_start"] = $this->_request->getParam('time-start');
    		$exercises["time_end"] = $this->_request->getParam('time-end');
    		$exercises["content"] = $this->_request->getParam('content');
    		$exercises["link"] = "";
    		if($exercises["name"] && $exercises["content"]){
    			/*
    			 * Xu ly upload file
    			 */
    			$error_upload = 0;
	    		if(($_FILES["file"]["name"])){

	    			$exercises["link"] = ExercisesModel::uploadFile();
	    			if (!preg_match('/\.(rar|zip)$/i',$exercises["link"])) {
	    				$error_upload = 1;
	    			}
	    		}
	    		if(!$error_upload){
		    		ExercisesModel::add($exercises);
		    		$this->view->success = 1;
		    		$this->view->error_upload = $error_upload;
	    		}
	    		else{
	    			$this->view->warning = 1;
	    		}
	    	//	Zend_Debug::dump($exercises["link"]);die;
    		}
    		else{
    			$this->view->warning = 1;
    		}
    		$this->view->exercises = $exercises;
    	}
    	
    	if($sj_id){
    		$sj_name = SubjectsModel::getNameSubject($sj_id);
    	//	Zend_Debug::dump($sj_name);die;
    		$this->view->sj_name = $sj_name;
    	}
    }
    
    /*
     * Action xu ly xem nhung bai tap nop
     */
    
    function submitExercisesAction(){
        $exercises = $this->_request->getParam('id');   
    	$list = ExercisesModel::getAllSubmitExercisesFromStudent($exercises);

        $sj_id = $this->_request->getParam('sj_id');   
        $name = SubjectsModel::getNameSubject($sj_id);
    	$this->view->list = $list;
        $this->view->name = $name;
        $this->view->sj_id = $sj_id;
    }
    
    
    function testAjaxAction(){
    	$layout = $this->_helper->layout();
    	$layout->disableLayout();
    	$list = ExercisesModel::getAllSubmitExercisesFromStudent();
    	$count = count($list);
   // 	$this->view->list = $list;
    	$output = array(
    			"sEcho" => 0,
    			"iTotalRecords" => $count,
    			"iTotalDisplayRecords" => 10,
    			"aaData" => $list
    	);
    	echo json_encode($output);
    	exit();
    }
    
     /*
     * Chấm điểm
     */

    public function scoreFileAction(){
        $e_id = $this->_request->getParam('e_id');
        $sj_id = $this->_request->getParam('sj_id');
        $this->view->sj_id = $sj_id;
        $name = SubjectsModel::getNameSubject($e_id);
        $this->view->e_id = $e_id;
        $this->view->name = $name;

        require_once 'file/excel/excel_reader.php';
        
        if($this->_request->getParam('submit') == 'Đồng ý'){
            /*
             * Thiết lập kích thước tối đa (10 MB) cho file sẽ upload lên.
            * Chỉ cho phép upload file định dạng xls
            */
            $maxSize = 1048576;
            $temp = preg_split('/[\/\\\\]+/', $_FILES["file"]["name"]);
            $filename = $temp[count($temp)-1];
             
            // Kiểm tra phần mở rộng của file xem có đúng định dạng hay không.
            if (preg_match('/\.(xls|xlsx)$/i', $filename )) {
                if($_FILES["file"]["size"] < $maxSize){
                    $dt = new TeacherModel();
                    $name_file = $dt->uploadFile();
                    //  echo $name_file;die;
                    /*
                     * Lấy file excel cần xử lý và require thư viện xử lý file excel.
                    * Nhung thu vien xu ly ma nguon mo
                    */
                    $filename= "file/excel/".$name_file;
    
    
                    /*
                     * Khoi tao doi tuong doc file excel
                    */
                    $data = new Spreadsheet_Excel_Reader($filename,true,"UTF-8");
                    $rowsnum = $data->rowcount($sheet_index=0); // lay so hang cua sheet
                    $colsnum =  $data->colcount($sheet_index=0); // lay so cot cua sheet
    
                    /*
                     * Đọc dữ liệu và ghi vào database.
                    */
                    for ($i=2;$i<=$rowsnum;$i++){
                        $max = 0;
                        /*
                         * Lay thong tin sv tu file excel
                         */
                        $point["id_students"] = StudentsModel::getIdStudentByShsv($data->val($i,2));
                        $point["id_exercises"] = $e_id;
                        $point["point"] = $data->val($i,5);
                        $point["note"] = $data->val($i,6);

                        if($point["id_students"] && $point["id_exercises"]){
                         //   PointModel::add($point);
                          //  Zend_Debug::dump($point);
                            PointModel::editPointOfStudent($point["point"],$point["note"],$point["id_students"],$point["id_exercises"],0,"");
                        }

                    }
                    $this->view->success = 1;
                }
                else{
    
                    $this->view->warning = 1;
                }
            }
            else{
                 
                $this->view->warning = 2;
            }
        }
        else if($this->_request->getParam('submit') == 'Send'){
            $max = $this->_request->getParam('max');
         //  echo $max;die;
            for($i=0; $i < $max; $i++){
                $point = $this->_request->getParam('point'.$i);
                $note = $this->_request->getParam('note'.$i);
                $id_sv = $this->_request->getParam('id_sv'.$i);
             //   echo 12;die;
             //   echo $point."   ".$note."  ".$id_sv."  ".$e_id;die;
                PointModel::editPointOfStudent($point,$note,$id_sv,$e_id,0,"");

            }

        }

        /*
        * Lấy thông tin về điểm của sinh viên.
        */
        $pointInfo = PointModel::getPointByIdExercises($e_id);
        $this->view->pointInfo = $pointInfo;

        $list_student = InfoClassModel::getStudentByIdSuject($sj_id);
        $this->view->list_student = $list_student;
    }
    
     /*
     * Xử lý xóa bai tap.
     */
    
    function deleteExAction(){
        $dt = new ExercisesModel();
        $request = $this->getRequest();
        $id = $request->getParam('id');
        if($id){
            $dt->delete("id=".$id);
        }
        exit();
    }
    
     /*
     * Xử lý chinh sua bai tap.
     */
    
    function editExAction(){
        $id_ex = $this->_request->getParam('id_ex');
        
        if($this->_request->isPost()){
            /*
             * Nhan du lieu dau vao
             */
            $exercises["name"] = $this->_request->getParam('exercises');
            $exercises["id_subjects"] =  $this->_request->getParam('id_subjects');
            $exercises["time_start"] = $this->_request->getParam('time-start');
            $exercises["time_end"] = $this->_request->getParam('time-end');
            $exercises["content"] = $this->_request->getParam('content');
            $exercises["link"] = $this->_request->getParam('file_old');
            $exercises["id"] = $id_ex;
            if($exercises["name"] && $exercises["content"]){
                /*
                 * Xu ly upload file
                 */

                $error_upload = 0;
                if($_FILES["file"]["name"]){

                    $exercises["link"] = ExercisesModel::uploadFile();
                    if (!preg_match('/\.(rar|zip)$/i',$exercises["link"])) {
                        $error_upload = 1;
                    }
                }
                if(!$error_upload){
                  //  echo 345;die;
                  //  Zend_Debug::dump($exercises);die;
                    ExercisesModel::edit($exercises);

                    $this->view->success = 1;
                    $this->view->error_upload = $error_upload;
                }
                else{
                    $this->view->warning = 1;
                }
            //  Zend_Debug::dump($exercises["link"]);die;
            }
            else{
                $this->view->warning = 1;
            }
            $this->view->exercises = $exercises;
        }
        
        if($id_ex){
            $data = ExercisesModel::getExById($id_ex);
        //    Zend_Debug::dump($data);die;
            $this->view->data = $data;
        }
    }
    
    
    /*
    * Giáo viên chấm điểm cho môn học
    */

    function scoreSubjectAction(){
        $sj_id = $this->_request->getParam('sj_id');
        $this->view->sj_id = $sj_id;

        $type_point = $this->_request->getParam('type-point');
        if(!$type_point) $type_point = 1;
        $this->view->type_point = $type_point;
      //  echo $type_point."  loai diem";
        require_once 'file/excel/excel_reader.php';
        
        if($this->_request->getParam('submit') == 'Đồng ý'){
            
            /*
             * Thiết lập kích thước tối đa (10 MB) cho file sẽ upload lên.
            * Chỉ cho phép upload file định dạng xls
            */
            $maxSize = 1048576;
            $temp = preg_split('/[\/\\\\]+/', $_FILES["file"]["name"]);
            $filename = $temp[count($temp)-1];
             
            // Kiểm tra phần mở rộng của file xem có đúng định dạng hay không.
            if (preg_match('/\.(xls|xlsx)$/i', $filename )) {
                if($_FILES["file"]["size"] < $maxSize){

                    $dt = new TeacherModel();
                    $name_file = $dt->uploadFile();
                    //  echo $name_file;die;
                    /*
                     * Lấy file excel cần xử lý và require thư viện xử lý file excel.
                    * Nhung thu vien xu ly ma nguon mo
                    */
                    $filename= "file/excel/".$name_file;

                    /*
                     * Khoi tao doi tuong doc file excel
                    */
                    $data = new Spreadsheet_Excel_Reader($filename,true,"UTF-8");
                    $rowsnum = $data->rowcount($sheet_index=0); // lay so hang cua sheet
                    $colsnum =  $data->colcount($sheet_index=0); // lay so cot cua sheet
    
                    /*
                     * Đọc dữ liệu và ghi vào database.
                    */

                    for ($i=2;$i<=$rowsnum;$i++){
                        $max = 0;
                        /*
                         * Lay thong tin sv tu file excel
                         */
                        $point["id_students"] = StudentsModel::getIdStudentByShsv($data->val($i,2));
                        $point["id_exercises"] = "";
                        $point["point"] = $data->val($i,5);
                        $point["note"] = $data->val($i,6);

                        if($point["id_students"]){
                         //   echo 233;die;
                            PointModel::editPointSubjectOfStudent($point["point"],$point["note"],$point["id_students"],0,$sj_id,$type_point);
                        }

                    }
                    $this->view->success = 1;
                }
                else{
    
                    $this->view->warning = 1;
                }
            }
            else{
                 
                $this->view->warning = 2;
            }
        }

        if($this->_request->getParam('submit') == 'Send'){
            $max = $this->_request->getParam('max');
         //  echo $max;die;
            for($i=0; $i < $max; $i++){
                $point = $this->_request->getParam('point'.$i);
                $note = $this->_request->getParam('note'.$i);
                $id_sv = $this->_request->getParam('id_sv'.$i);
             //   echo 12;die;
             //   echo $point." diem  ".$note." chu y ".$id_sv." id sv ".$e_id."  id bt";die;
                PointModel::editPointSubjectOfStudent($point,$note,$id_sv,0,$sj_id,$type_point);
            }
        }
        $sj_name = SubjectsModel::getNameSubject($sj_id);
        $this->view->sj_name = $sj_name;
        $list_student = InfoClassModel::getStudentByIdSuject($sj_id);
        $this->view->list_student = $list_student;

        $typePoint = $this->_request->getParam('type-point');
        if(!$typePoint) $typePoint = 1;
        $pointStudent = PointModel::getPointByIdSubjectAndInfoExtend($sj_id,$typePoint);
        $this->view->pointStudent = $pointStudent;
    }
}